package com.sskj.common.encrypt;

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public class RSAUtils {

    public static final String RSA_ALGORITHM = "RSA/None/PKCS1Padding";
    /** 指定key的大小 */
    private static int KEYSIZE = 1024;

//    public static final String PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkibU+BPX0CRDZdN4rbUqfkakYhauYgmSAmw+gNWChBRNm0f/dpFaOsPMLRWFt2SQrn5apy9JLuAZQsmosh3nf3bZFEnrfG4Pzs/Uc3hhlHCj5zDjTXJRbyVVdgs4leCaBPktDRI52xvLHwg7MqbA9RZHAIxrOYbr9sREtbfnAlwIDAQAB";
    public static final String PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZ4CaAE8gS79vZ1bE4n0L40N9p\n" +
        "M76rvD0OBN6e24FMtKeKzR7iy25FVebm2Vlq6KJerS8c5AZOTfK0D0Xs53NX8m7f\n" +
        "F/qoVSxKfTa8gO5BnmSgZm2txKDZ1As684c7WjJlmd5SRyGoRr72HxNxbTqLoSDx\n" +
        "W9/QSd+Lp9D9uPaiYQIDAQAB";

//    public static final String PRIVATE_KEY="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKSJtT4E9fQJENl03ittSp+RqRiFq5iCZICbD6A1YKEFE2bR/92kVo6w8wtFYW3ZJCuflqnL0ku4BlCyaiyHed/dtkUSet8bg/Oz9RzeGGUcKPnMONNclFvJVV2CziV4JoE+S0NEjnbG8sfCDsypsD1FkcAjGs5huv2xES1t+cCXAgMBAAECgYAOHtn/YjzwCN3O+7jxWyYd/vSBwT79DfutZHaj1iYzy2ljLT8weKELtTiLzWl+HDYpdD8MKrd302mKAAsdRTHP7EyYiM1aewa5WNZhVVQLEThlTgANKSP3Aj8RfDpFwNWMjdx9OV/8YGG/8v9P+C9HSNACSZagWAQruMQpAP+KoQJBANJgHdoUZ+UEI9+o8RWvSayU8NtkQiGMO4BowhlMe0ntVtsbzdD3tVv/DlHUgqXOnkldfmd8NLx5ZoBY6cf80+cCQQDIOLoNud6QR2J8/n82c8z71syFtrtDkWWoVqhXLKQL0HHcKpHIvZ9uOTaHfWmM9zw10I5PWtgn7QSGGVTBYRfRAkEAkpu5MgmWfdtsxKmPmXUW+taxI7OzAn4f2VUoL0lFgjeMmBXAUSjPktUkvZJDmhlr5eTp+mRsvAw+iqNsCJsBcQJAJrVA0vKCIqaKVdvlwCM3F+D4/UjMf02Wt6q5NNE+jcIooQXh1UtDjU2mSx9lzojlrQm62YCYlW9vFnXDOveIYQJALsra55AKIjK1DSP5qadN3/YC+3Mkn2vSBXB+xvneljsN+3cQ80/0KZD2G0YhyW+rE9u5dTkmpKyBPH0h8V6hRg==";
    public static final String PRIVATE_KEY="MIICXQIBAAKBgQCZ4CaAE8gS79vZ1bE4n0L40N9pM76rvD0OBN6e24FMtKeKzR7i\n" +
        "y25FVebm2Vlq6KJerS8c5AZOTfK0D0Xs53NX8m7fF/qoVSxKfTa8gO5BnmSgZm2t\n" +
        "xKDZ1As684c7WjJlmd5SRyGoRr72HxNxbTqLoSDxW9/QSd+Lp9D9uPaiYQIDAQAB\n" +
        "AoGAB6QsdUbGND6KDebBPr0V79I7jfdeXBvkckpGnd/rq1n7SfbGtl+A0duitEsN\n" +
        "2DPGQGpcQRSHxaK0T0HE6K9TuHHa4AcIJfXnWSakNvj1QMGpr/a//b8U5gqXWSw0\n" +
        "y4ZTZH+UVVC5C98wt/nWFfvzk4vGYWQbhDMBFXhNltgNxuECQQCoFoRSFpCkujYA\n" +
        "4ofO1Ig1D6zb9XiTyTE0I1byH5vjxrm61d2Vx5LUbEGWS9LhV4gR5oM7nswr7Fhn\n" +
        "bVzp+3QJAkEA6lq5QFntIUJyaCnCd6Nc6d4ByIk87t/UZl/dv2lLwi1OvVcf2mxn\n" +
        "eH2kAuUhjWBmDcxpIcuNVpo8xz9kvXhBmQJABkFoRUHPukGv1tKXaUwhkY/2x+zX\n" +
        "wvA+44jZKIOiopR3vwtMhtF5lmw8+KHzxC0kxD3G7oYXZR8Tny3DwnV4OQJBAKqx\n" +
        "RbjfRt4wvY+syt3E+QnGD9p2SxFZqiSesq6WDP3zbiRubt7ykjKqoGkTZurISczH\n" +
        "E9PvpJRtZtNhEwkFrBECQQCS9ekbwBn0IjluHYrA5HMlxgrZDhQXwzqCCx/g8uqY\n" +
        "oKA2P8lucSGfKEam4Hh83tXoIDZX/HdUoZ3sG+55LhEf";


    public static void main(String[] args) {


    }

    /**
     * 生成密钥对
     */
    public static Map<String, String> generateKeyPair() throws Exception {
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom sr = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        kpg.initialize(KEYSIZE, sr);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();
        String pub = new String(Base64Utils.encode(publicKeyBytes),
                "UTF-8");
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();
        String pri = new String(Base64Utils.encode(privateKeyBytes),
                "UTF-8");

        Map<String, String> map = new HashMap<String, String>();
        map.put("publicKey", pub);
        map.put("privateKey", pri);
        RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
        BigInteger bint = rsp.getModulus();
        byte[] b = bint.toByteArray();
        byte[] deBase64Value = Base64Utils.encode(b);
        String retValue = new String(deBase64Value);
        map.put("modulus", retValue);
        return map;
    }


    /**
     * 加密方法 source： 源数据
     */
    public static String encrypt(String source, String publicKey)
            throws Exception {
        Key key = getPublicKey(publicKey);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        return new String(Base64Utils.encode(b1),
                "UTF-8");
    }


    /**
     * 加密方法 source： 源数据
     */
    public static String encryptByPrivate(String source, String privateKey)
            throws Exception {
        Key key = getPrivateKey(privateKey);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        return new String(Base64Utils.encode(b1),
                "UTF-8");
    }

    /**
     * 解密算法 cryptograph:密文
     */
    public static String decrypt(String cryptograph, String privateKey)
            throws Exception {
        Key key = getPrivateKey(privateKey);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] b1 = Base64Utils.decode(cryptograph.getBytes());
        /** 执行解密操作 */
        byte[] b = cipher.doFinal(b1);
        return new String(b);
    }



    /**
     * 解密算法 cryptograph:密文
     */
    public static String decryptByPublic(String cryptograph, String publicKey)
            throws Exception {
        Key key = getPublicKey(publicKey);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] b1 = Base64Utils.decode(cryptograph.getBytes());
        /** 执行解密操作 */
        byte[] b = cipher.doFinal(b1);
        return new String(b);
    }

    /**
     * 得到公钥
     *
     * @param key 密钥字符串（经过base64编码）
     * @throws
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                Base64Utils.decode(key.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 得到私钥
     *
     * @param key 密钥字符串（经过base64编码）
     * @throws
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
                Base64Utils.decode(key.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

}
